﻿//  Copyright (c) 2009 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;

namespace DNA.Mvc.jQuery
{
    public static class ImageToggleButtonExtensions
    {
        public static MvcHtmlString ImageToggleButton(this AjaxHelper helper,ImageToggleButtonOptions options)
        {
            if (options == null)
                throw new ArgumentNullException("options");

            var link = new TagBuilder("a");
            var img = new TagBuilder("img");
            var text = new TagBuilder("span");

            img.MergeAttribute("alt", "");
            img.MergeAttribute("src", options.ImageUrl);
            if (!string.IsNullOrEmpty(options.ImageCssClass))
                img.MergeAttribute("class", options.ImageCssClass);

            if (!string.IsNullOrEmpty(options.ImageStyleText))
                img.MergeAttribute("style", options.ImageStyleText);

            if (!string.IsNullOrEmpty(options.TextCssClass))
                text.MergeAttribute("class", options.TextCssClass);

            if (!string.IsNullOrEmpty(options.TextStyleText))
                text.MergeAttribute("style", options.TextStyleText);
            text.SetInnerText(options.Text);

            string id = Guid.NewGuid().ToString().Substring(0, 5);
            link.MergeAttribute("id", id);
            link.MergeAttribute("href", "javascript:void(0);");

            if (!string.IsNullOrEmpty(options.CssClass))
                link.MergeAttribute("class", options.CssClass);

            if (!string.IsNullOrEmpty(options.StyleText))
                link.MergeAttribute("style", options.StyleText);

            link.InnerHtml = img.ToString(TagRenderMode.SelfClosing) + text.ToString();
            var scripts = new StringBuilder();
            scripts.Append("$(\"#" + id + "\").toggle(function(){")
                     .Append("$(this).find('img').attr('src','" + options.ToggleImageUrl + "');")
                     .Append("$(this).find('span').html('" + options.ToggleText + "');")
                     .Append(options.OnClientClick)
                     .Append("},function(){")
                     .Append("$(this).find('img').attr('src','" + options.ImageUrl + "');")
                     .Append("$(this).find('span').html('" + options.Text + "');")
                     .Append(options.OnClientToggleClick)
                     .Append("});");
            helper.RegisterStartupScript(scripts.ToString());
            return MvcHtmlString.Create(link.ToString());
        }
    }
}
